import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import handler as api_key_handler, get_api_key

import urllib
import hmac
import logging
import hashlib

def verify_api_sig(request_url, secret_key, api_sig):
    """ Verify request"""
    sig = hmac.new(secret_key,
                   msg=request_url,
                   digestmod=hashlib.sha1).hexdigest()
    logging.info(sig)
    return api_sig == sig

def check_request(request):
    api_key = request.get('api_key')
    api_sig = request.get('api_sign')
    api = get_api_key(api_key)
    if not api or not api_sig:
        return None
    
    # 1. Delete api_sig
    params = dict([x.split('=')
                   for x in request.query_string.split('&')])
    del params['api_sig']
    
    # 2. Sort parameter a- z
    tmp = params.item()
    tmp.sort()
    
    # 3. Rebuild URL request
    query_string = '&'.join([k+'='+urllib.quote(str(v))
                             for (k,v) in tmp])
    
    # 4. Verify signature
    return verify_api_sig(request.path + '?' + str(query_string),
                   api.secret_key,
                   api_sig)


class HttpServices(webapp.RequestHandler):
    def common(self, handler, method):
        
        self.response.out.headers['Content-Type'] = 'application/json; charset-utf-8'
        if (not check_request(handler.request)):
            #failed
            self.response.out.write('{"class" : "IncorrectSignature"}')
            return
        #verify
        self.response.out.write('Hello %s' % self.request.get('name'))
    
    def post(self):
        self.common(self,'POST')

    def get(self):
        self.common('GET')
        
        
class MainPage(webapp.RequestHandler):
    
    
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'main.html')
        self.response.out.write(template.render(path,  True))
    
    
    
    
application = webapp.WSGIApplication([('/', MainPage),
                                      ('/api_key/add', api_key_handler.AddApiKey),
                                      ('/bkitmobile/hello', api_key_handler.AddApiKey),
                                      ('/api_key/list', api_key_handler.ListApiKey),
                                      ('/api_key/edit', api_key_handler.EditApiKey),
                                      ('/api_key/delete', api_key_handler.DelApiKey)
                                        ], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()